#include "MeasurementManagementPlugin.h"
#include <QDebug>
#include "MeasurementControlWidget.h"
#include "CameraPluginInterface.h"

MeasurementManagementPlugin::MeasurementManagementPlugin(QObject *parent) :
    CameraPluginInterface(parent), m_pMeasurementAlgorithmManager(nullptr), 
    m_pMeasurementControlWidget(nullptr) {}

MeasurementManagementPlugin::~MeasurementManagementPlugin() {
    if (m_pMeasurementControlWidget) {
        m_pMeasurementControlWidget = nullptr;
    }
    if (m_pMeasurementAlgorithmManager) {
        delete m_pMeasurementAlgorithmManager;
        m_pMeasurementAlgorithmManager = nullptr;
    }
}

void MeasurementManagementPlugin::initialize() {

    if (!m_pMeasurementAlgorithmManager)
    {
        m_pMeasurementAlgorithmManager = new MeasurementAlgorithmManager;
        // 连接算法注册信号到UI组件
        connect(m_pMeasurementAlgorithmManager, &MeasurementAlgorithmManager::algorithmRegistered, this, [this](const QString& algorithmName, const QString& iconPath)
        {
            // 处理算法注册信号，转发给UI组件
            qDebug() << "Measurement algorithm registered: " << algorithmName;

             // 动态添加测量算法按钮
            if (m_pMeasurementControlWidget) {
                m_pMeasurementControlWidget->addMeasurementAlgorithmButton(algorithmName, iconPath);
            }
        });

        // 连接算法管理器的测量完成信号
        connect(m_pMeasurementAlgorithmManager, &MeasurementAlgorithmManager::measurementProcessingCompleted,
                this, [](const QString& imageId, const QVariantMap& measurementResult, const QString& algorithmName) {
            // 处理测量完成结果，可上报给图像管理插件或其他组件
            qDebug() << "Measurement completed for: " << imageId << " with algorithm: " << algorithmName;
        });
        
        // 连接算法管理器的其他信号到测量控制界面
        connect(m_pMeasurementAlgorithmManager, &MeasurementAlgorithmManager::resultWidgetReady,this,
                [this](const QString& algorithmName, QWidget* widget)
        {
           Q_UNUSED(algorithmName)
           emit this->registerWidgetToDock(DockWidgetType::MeasurementResults,widget);
        });
        connect(m_pMeasurementAlgorithmManager, &MeasurementAlgorithmManager::measurementToolWidgetRegistered,
                [this](const QString& algorithmName, QWidget* widget)
        {
            Q_UNUSED(algorithmName)
            m_pMeasurementControlWidget->registerMeasurementToolWidget(widget);
        });
    }

    if (!m_pMeasurementControlWidget)
    {
        m_pMeasurementControlWidget = new MeasurementControlWidget(m_pMeasurementAlgorithmManager);
        emit registerWidgetToDock(DockWidgetType::MeasurementTools, m_pMeasurementControlWidget);
    }
    connect(m_pMeasurementControlWidget,&MeasurementControlWidget::measurementImageRequested,this,[this](const QString& algorithmName, const QVariantMap& parameters)
    {
        qDebug() << "Sending measurement request to ImageManagement plugin for algorithm: " << algorithmName;
        
        // 向图像管理插件发送测量请求消息
        // 消息格式: "CMD_MEASUREMENT_REQUEST:algorithmName:measurementType"
        QString measurementType = parameters.value("measurementType", "").toString();
        QString message = QString(CMD_MEASUREMENT_REQUEST ":%1:%2").arg(algorithmName).arg(measurementType);
        emit pluginMessageSent(pluginName(), message, IMAGE_MANAGEMENT_PLUGIN_NAME);
    });
    m_pMeasurementAlgorithmManager->initialize();
}

QString MeasurementManagementPlugin::pluginName() const {
    return MEASUREMENT_MANAGEMENT_PLUGIN_NAME;
}

QString MeasurementManagementPlugin::description() const {
    return "用于测量控制和测量算法管理的插件";
}

// 统一处理撤销和重做操作的私有函数
void MeasurementManagementPlugin::handleUndoRedoOperation(const QString& imageGuid, bool isUndo)
{
    m_pMeasurementControlWidget->restoreDefaultMeasurementTools();
    // 获取当前操作值
    QVariantList args;
    args << imageGuid;
    QVariant operationValue;
    bool success = requestPluginFunctionCall(
                IMAGE_MANAGEMENT_PLUGIN_NAME,
                "getCurrentOperationValue",
                args,
                operationValue
                );

    if (success && operationValue.isValid() && operationValue.canConvert<QVariantMap>()) {
        QVariantMap params = operationValue.value<QVariantMap>();
        // 根据操作类型选择使用previousValue(undo)或currentValue(redo)
        const QString valueKey = isUndo ? "previousValue" : "currentValue";
        if (params.contains(valueKey)) {
            QVariantMap measurementParams = params[valueKey].toMap();
            // 检查是否包含算法名称、测量类型和测量结果
            if (measurementParams.contains("algorithmName") && 
                measurementParams.contains("measurementType") && 
                measurementParams.contains("measurementResult")) {
                
                QString algorithmName = measurementParams["algorithmName"].toString();
                QString measurementType = measurementParams["measurementType"].toString();
                QVariantMap measurementResult = measurementParams["measurementResult"].toMap();

                // 1. 根据测量算法名称和测量类型设置测量按钮选中
                if (m_pMeasurementControlWidget) {
                    m_pMeasurementControlWidget->setMeasurementAlgorithmButtonSelected(algorithmName, true);
                }

                // 2. 通过测量管理类将测量结果的参数设置到测量算法中
                if (m_pMeasurementAlgorithmManager) {
                    m_pMeasurementAlgorithmManager->setMeasurementResult(algorithmName, measurementResult);
                }
            }
        }
    }
}

void MeasurementManagementPlugin::onPluginMessage(const QString& sender, const QString& message)
{
    Q_UNUSED(sender)
    qDebug()<<MEASUREMENT_MANAGEMENT_PLUGIN_NAME<<"rcv:"<<message<<"from"<<sender;
    // 处理图像被选中的消息
    if (message.startsWith(CMD_IMAGE_SELECTED":")) {
        // 解析消息，格式为：CMD_IMAGE_SELECTED:图像GUID
        QStringList parts = message.split(":");
        if (parts.size() >= 2) {
            QString imageGuid = parts[1];
            // 启用测量按钮
            if (m_pMeasurementControlWidget) {
                m_pMeasurementControlWidget->enableAllAlgorithmButtons(true);
            }
        }
    }
    // 处理图像未选中/清空的消息
    else if (message.startsWith(CMD_IMAGE_DESELECTED ":")) {
        // 禁用所有测量按钮
        if (m_pMeasurementControlWidget) {
            m_pMeasurementControlWidget->enableAllAlgorithmButtons(false);
        }
    }
    // 处理来自图像管理插件的测量准备完成消息
    else if (message.startsWith(CMD_MEASUREMENT_READY ":")) {
        // 消息格式: "CMD_MEASUREMENT_READY:algorithmName:imageId:measurementType"
        QStringList parts = message.split(":");
        if (parts.size() >= 4) {
            QString algorithmName = parts[1];
            QString imageId = parts[2];
            QString measurementType = parts[3];
            
            // 调用封装的处理函数
            executeMeasurement(algorithmName, imageId, measurementType);
        }
    }
    // 处理缩放变化消息
    else if (message.startsWith(CMD_SCALE_CHANGED ":")) {
        // 消息格式: "CMD_SCALE_CHANGED:imageGuid:lengthRatio:timeRatio:wavelengthRatio:lengthUnit:timeUnit:wavelengthUnit:xUnit:yUnit"
        QStringList parts = message.split(":");
        if (parts.size() >= 3) {
            QString imageGuid = parts[1];
            // 这里应该调用setUnitConversionForAlgorithm方法，因为消息包含了完整的单位转换信息
            qreal scale = parts[2].toDouble();

            // 调用单位转换方法更新完整的转换信息
            if (m_pMeasurementAlgorithmManager) {
                m_pMeasurementAlgorithmManager->setScaleForAlgorithm(imageGuid, scale);
            }
        }
    }
    // 处理单位转换变化消息
    else if (message.startsWith(CMD_UNIT_CONVERSION_CHANGED ":")) {
        // 消息格式: "CMD_UNIT_CONVERSION_CHANGED:imageGuid:xUnit:yUnit:xRatio:yRatio"
        QStringList parts = message.split(":");
        if (parts.size() >= 10) {
            QString imageGuid = parts[1];
            // 这里应该调用setUnitConversionForAlgorithm方法，因为消息包含了完整的单位转换信息
            qreal lengthRatio = parts[2].toDouble();
            qreal timeRatio = parts[3].toDouble();
            qreal wavelengthRatio = parts[4].toDouble();
            QString lengthUnit = parts[5];
            QString timeUnit = parts[6];
            QString wavelengthUnit = parts[7];
            QString xUnit = parts[8];
            QString yUnit = parts[9];


            // 调用单位转换方法更新完整的转换信息
            if (m_pMeasurementAlgorithmManager) {
                m_pMeasurementAlgorithmManager->setUnitConversionForAlgorithm(imageGuid, xUnit, yUnit,
                                                                            lengthRatio, timeRatio, wavelengthRatio,
                                                                            lengthUnit, timeUnit, wavelengthUnit);
            }
        }
    }
    // 处理来自ImageManagementPlugin的undo和redo消息
    else if (message.startsWith("CMD_OPERATION_UNDO_SUCCESS:")) {
        // 解析消息，格式为：CMD_OPERATION_UNDO_SUCCESS:图像GUID:操作类型:描述
        QStringList parts = message.split(":");
        if (parts.size() >= 4) {
            QString imageGuid = parts[1];
            QString operationType = parts[2];
            QString description = parts[3];

            qDebug() << "Received undo success message for image: " << imageGuid << ", operationType: " << operationType << ", description: " << description;

            // 只处理图像测量相关的操作
            if (operationType == "ImageMeasurement") {
                // 调用统一的撤销/重做处理函数，传入true表示撤销操作
                handleUndoRedoOperation(imageGuid, true);
            }
        }
    }
    // 处理redo成功消息
    else if (message.startsWith("CMD_OPERATION_REDO_SUCCESS:")) {
        // 解析消息，格式为：CMD_OPERATION_REDO_SUCCESS:图像GUID:操作类型:描述
        QStringList parts = message.split(":");
        if (parts.size() >= 4) {
            QString imageGuid = parts[1];
            QString operationType = parts[2];
            QString description = parts[3];

            qDebug() << "Received redo success message for image: " << imageGuid << ", operationType: " << operationType << ", description: " << description;

            // 只处理图像测量相关的操作
            if (operationType == "ImageMeasurement") {
                // 调用统一的撤销/重做处理函数，传入false表示重做操作
                handleUndoRedoOperation(imageGuid, false);
            }
        }
    }
}

void MeasurementManagementPlugin::executeMeasurement(const QVariant& algorithmName, const QVariant& imageId, const QVariant& measurementType)
{
    qDebug()<<"executeMeasurement";
    // 准备测量参数
    QVariantMap parameters;
    parameters["ImageGuid"]=imageId;
    parameters["MeasurementType"] = measurementType.toString();

    // 从图像管理插件获取显示图像
    QVariantList imageArgs;
    imageArgs << imageId;
    QVariant displayImage;
    bool imageSuccess =emit requestPluginFunctionCall(
        IMAGE_MANAGEMENT_PLUGIN_NAME, 
        "getDisplayImage",
        imageArgs, 
        displayImage
    );
    
    if (imageSuccess && displayImage.isValid()) {
        parameters["DisplayImage"] = displayImage;
    }

    // 从图像显示插件获取画板
    QVariantList sceneArgs;
    sceneArgs << imageId;
    QVariant scenePointer;
    bool sceneSuccess =emit requestPluginFunctionCall(
        GRAPHICS_DISPLAY_PLUGIN_NAME, 
        "getScenePointer", 
        sceneArgs, 
        scenePointer
    );
    
    if (sceneSuccess && scenePointer.isValid()) {
        parameters["Canvas"] = scenePointer;
    }

    // 从图像管理插件获取单位转换信息
    QVariantList conversionArgs;
    conversionArgs << imageId;
    QVariant conversionInfo;
    bool conversionSuccess =emit requestPluginFunctionCall(
        IMAGE_MANAGEMENT_PLUGIN_NAME, 
        "getImageConversionInfo", 
        conversionArgs, 
        conversionInfo
    );
    
    if (conversionSuccess && conversionInfo.isValid() && conversionInfo.canConvert<QVariantMap>()) {
        QVariantMap conversionMap = conversionInfo.value<QVariantMap>();
        parameters["UnitConversion"] = conversionMap;
    }

    // 从图像显示插件获取缩放比例
    QVariantList scaleArgs;
    scaleArgs << imageId;
    QVariant scale;
    bool scaleSuccess =emit requestPluginFunctionCall(
        GRAPHICS_DISPLAY_PLUGIN_NAME, 
        "getCurrentScale", 
        scaleArgs, 
        scale
    );
    
    if (scaleSuccess && scale.isValid()) {
        parameters["ImageScale"] = scale;
    }

    // 从图像显示插件获取偏移值
    QVariantList offsetArgs;
    offsetArgs << imageId;
    QVariant offsetInfo;
    bool offsetSuccess =emit requestPluginFunctionCall(
        GRAPHICS_DISPLAY_PLUGIN_NAME, 
        "getCurrentOffset", 
        offsetArgs, 
        offsetInfo
    );
    if (offsetSuccess && offsetInfo.isValid() && offsetInfo.canConvert<QSize>())
    {
        parameters["ImageOffset"]= offsetInfo;
    }
    // 使用算法管理器执行测量
    if (m_pMeasurementAlgorithmManager)
    {
        m_pMeasurementAlgorithmManager->processMeasurement(algorithmName.toString(),imageId.toString());
        m_pMeasurementAlgorithmManager->setAlgorithmParameters(algorithmName.toString(),imageId.toString(), parameters);
    }
}
